package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 添加
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithDishFlavor(DishDto dishDto) {
        //    先保存菜品
        this.save(dishDto);
        //    在保存口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //给每个口味设置对应的菜品ID
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public DishDto findByIdWithFlavor(Long id) {
        //1.查询菜品数据 select * from dish where id=?
        Dish dish = this.getById(id);
        //2.查询口味数据(是一个集合) select * from dish_flavor where dish_id=?
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
        //3.合并Dish+dishFlavor=disDto
        DishDto dishDto = new DishDto();//DishDto=Dish+List<DishFlavor>
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavorList);
        return dishDto;
    }

    /**
     * 根据ID修改菜品和口味数据
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateByIdWithFlavor(DishDto dishDto) {
        //1.先更新菜品数据 update dish set xxx=yyy where id=?
        this.updateById(dishDto);

        //2.删除菜品对应的所有口味数据 delete from dish_flavor where dish_id=?
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //3.添加提交的所有口味数据
        List<DishFlavor> dishDtoFlavors = dishDto.getFlavors();
        //3.1给每个菜品口味设置dishId
        dishDtoFlavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishDtoFlavors);
    }
}